import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
} from 'react-native';

import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import Loading from "../../utils/Loading";
import { ToastToUser } from '../../utils/CustomToast';
import StatusBarSelf from '../../components/StatusBarSelf';

import { WebView as HXCommonWebView } from "react-native-webview";
import ContractAttachment from "./ContractAttachment"

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;

let intervalId;

let navigation

export default class ConfirmInfosPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            chooseType: true,
            templateList: [],
            contractInfos: [],
            contractNo: '',
            downloadUrl: '',

            attachmentFileList:[],
            localImgList:[],

            orderNo:'',
            buyerEsignAuthId:''
        }
    }

    componentWillUnmount() {
        clearInterval(this.intervalId);
    }

    componentDidMount() {
        if (this.props.route.params.participants && this.props.route.params.components) {
            this.setState({
                templateList: JSON.parse(this.props.route.params.participants),
                contractInfos: JSON.parse(this.props.route.params.components),
                contractNo: this.props.route.params.contractNo
            }, function () {
                // console.log(this.state.contractNo)
                // console.log(this.state.templateList)
                // console.log(this.state.contractInfos)
                this.intervalId = setInterval(() => this.getcontractNoInfo(), 1000);

            })
           
        }else if(this.props.route.params.orderNo){
            this.setState({
                orderNo: this.props.route.params.orderNo,
                buyerEsignAuthId: this.props.route.params.buyerEsignAuthId
            }, function () {
                this.getSystemTransactionContract()

            })
        }

    }


    getSystemTransactionContract(){
        let param = {
            orderNo	: this.state.orderNo,
            operator: Constant.userInfo.fullname ? Constant.userInfo.fullname : Constant.userInfo.userId,
            buyerEsignAuthId: this.state.buyerEsignAuthId,
        }

        if (this.Loading) {
            this.Loading.show();
        }


        HttpUtils.postRequest(HttpUrls.createSystemTransactionContract, param)
            .then((result) => {
                

                if (this.Loading) {
                    this.Loading.hide();
                }             

            let tempArr=[]
        for (let i = 0; i < result.data.participants.length; i++) {
                let item=result.data.participants[i]
                for(let j = 0; j < item.components.length; j++){
                    let finalItem=item.components[j]
                    let temp={}
                    temp.participantFlag=item.participantFlag
                    temp.componentName=finalItem.componentName
                    temp.componentValue=finalItem.componentValue
                    temp.showIndex=j
                    tempArr.push(temp)
                }
        }

                let code = result.code

                if (code == 0) {
                

                 this.setState({
                    templateList:result.data.participants,
                    contractNo:result.data.contractNo,
                    contractInfos:tempArr
                    }, function () {
                      
                        this.intervalId = setInterval(() => this.getcontractNoInfo(), 1000);

                    })
       
                } else {
                    // ToastToUser(result.msg)
                }
            })
            .catch((error) => {

            });
    }



    getcontractNoInfo() {
        let param = {
            contractNo: this.state.contractNo,
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
        }

        HttpUtils.getRequest(HttpUrls.downloadPdf, param)
            .then((result) => {
           
                if (this.Loading) {
                    this.Loading.hide();
                }

                let code = result.code

                if (code == 0) {

                    clearInterval(this.intervalId);

                    
                     this.setState({
                            downloadUrl: 'https://m-dev.shuaiche.com/pdfView?url='+result.data
                        })
       
                } else {
                    // ToastToUser(result.msg)
                }
            })
            .catch((error) => {

            });
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                {/* 顶部切换 */}
                <StatusBarSelf />
                {/* 顶部的切换 */}
                <View style={styles.toplayout}>
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={this.chooseTop.bind(this, 1)}
                    >
                        <View style={styles.privewTop}>
                            <Text style={!this.state.chooseType ? styles.topTitleChoose : styles.topTitle}>合同预览</Text>
                            <View style={!this.state.chooseType ? styles.bottomCheck : null}></View>
                        </View>
                    </TouchableOpacity>

                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={this.chooseTop.bind(this, 2)}
                    >
                        <View style={styles.privewTop}>
                            <Text style={this.state.chooseType ? styles.topTitleChoose : styles.topTitle}>信息确认</Text>
                            <View style={this.state.chooseType ? styles.bottomCheck : null}></View>
                        </View>
                    </TouchableOpacity>
                </View>

                {/* 信息展示 */}
                {
                    this.state.chooseType
                        ?
                        <ScrollView style={{ marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 50 : 50 }}>
                            <View style={styles.commonTitlsContainer}>
                                <Text style={styles.commonTitle}>签署方信息</Text>
                                <View style={styles.borderBottom} ></View>
                            </View>

                            <View>
                                {this.state.templateList.map((template, index) => (
                                    <View key={index}>
                                        {/* 标题 */}
                                        {
                                            template['participantFlag']
                                                ?
                                                <View style={styles.itemContainer}>
                                                    <Text style={styles.titleValue}>{template['participantFlag']}</Text>
                                                    <View style={styles.typeContainer}>
                                                        <Text style={styles.typeText}>{template['participantType'] == 1 ? '企业' : '个人'}</Text>
                                                    </View>
                                                    <View style={styles.borderBottom} ></View>
                                                </View>
                                                :
                                                null
                                        }
                                        {/* 企业名称 */}
                                        {
                                            template['orgName']
                                                ?
                                                <View style={styles.itemContainer}>
                                                    <Text style={styles.commonKey}>企业名称</Text>
                                                    <Text style={styles.commonValue}>{template['orgName']}</Text>
                                                    <View style={styles.borderBottom} ></View>
                                                </View>
                                                :
                                                null
                                        }
                                        {/* 姓名 */}
                                        {
                                            template['psnName'] || template['transactorName']
                                                ?
                                                <View style={styles.itemContainer}>
                                                    <Text style={styles.commonKey}>姓名</Text>
                                                    <Text style={styles.commonValue}>{template['psnName'] || template['transactorName']}</Text>
                                                    <View style={styles.borderBottom} ></View>
                                                </View>
                                                :
                                                null
                                        }
                                        {/* 手机号 */}
                                        {
                                            template['psnAccount'] || template['transactorPsnAccount']
                                                ?
                                                <View style={styles.itemContainer}>
                                                    <Text style={styles.commonKey}>手机号</Text>
                                                    <Text style={styles.commonValue}>{template['psnAccount'] || template['transactorPsnAccount']}</Text>
                                                    <View style={styles.borderBottom} ></View>
                                                </View>
                                                :
                                                null
                                        }
                                    </View>
                                ))}
                            </View>

                            <View style={[styles.commonTitlsContainer, { marginTop: 10 }]}>
                                <Text style={styles.commonTitle}>合同信息</Text>
                                <View style={styles.borderBottom} ></View>
                            </View>

                            <View>
                                {this.state.contractInfos.map((template, index) => (
                                    <View>
                                        {template['showIndex'] == 0 ? (
                                            <View style={styles.itemContainer}>
                                                <Text style={styles.commonTitle}>{template['participantFlag']}</Text>
                                                <View style={styles.borderBottom}></View>
                                            </View>
                                        ) : null}
                                        <View key={index} style={styles.itemContainer}>
                                            <Text style={styles.commonKey}>{template['componentName']}</Text>
                                            <Text style={styles.commonValue}>{template['componentValueShow'] || template['componentValue']}</Text>
                                            <View style={styles.borderBottom} ></View>
                                        </View>
                                    </View>

                                ))}
                            </View>

                            {
                                this.props.route.params.localImgList && (JSON.parse(this.props.route.params.localImgList)).length>0
                                ?
                            <View style={{ backgroundColor: 'white', marginTop: 10 }}>
                                <ContractAttachment
                                    localImgList={JSON.parse(this.props.route.params.localImgList)}
                                    attachmentFileList={JSON.parse(this.props.route.params.attachmentFileList)}
                                    carId={''}
                                    maintenanceRecordPdf={''}
                                    detectionReportPdf={''}
                                    isOnlyShow={true}>

                                </ContractAttachment>
                            </View>
                                :
                                null
                                
                            }
                        

                        </ScrollView>
                        :
                        <View style={{ marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 50 : 50, alignItems: 'center', justifyContent: 'center', flex: 1 }}>
                            {
                                this.state.downloadUrl
                                    ?
                                    <HXCommonWebView style={{ width: screenW, flex: 1 }} source={{ uri: this.state.downloadUrl }} />
                                    :
                                    <Text style={{ fontSize: 16, color: '#333333' }}>数据加载中请稍后...</Text>
                            }

                        </View>
                }
                <View style={[styles.bottomContainer, { bottom: Constant.isIPhoneX ? Constant.bottomHeight : 0 }]}>
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={this.beforeSubmit.bind(this)}
                    >
                        <View style={styles.beforeContainer}>
                            <Text style={styles.beforeTitle}>上一步</Text>
                        </View>
                    </TouchableOpacity>

                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={this.afterSubmit.bind(this)}
                    >
                        <View style={styles.afterContainer}>
                            <Text style={styles.beforeTitle}>提交并签署</Text>
                        </View>
                    </TouchableOpacity>
                </View>

                <Loading onRef={(ref) => (this.Loading = ref)} />

            </View>
        )
    }

    chooseTop(type) {
        if (type == 1) {
            this.setState({
                chooseType: false
            })
        } else {
            this.setState({
                chooseType: true
            })
        }
    }

    beforeSubmit() {
        navigation.goBack()
    }

    afterSubmit() {
        let param = {
            contractNo: this.state.contractNo,
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
            operator: Constant.userInfo.fullname ? Constant.userInfo.fullname : Constant.userInfo.userId,
        }

        if (this.Loading) {
            this.Loading.show();
        }


        HttpUtils.postRequest(HttpUrls.contractProdstart, param)
            .then((result) => {
                console.log(result)
                if (this.Loading) {
                    this.Loading.hide();
                }

                let code = result.code
                ToastToUser(result.msg)
                if (code == 0) {

                    try {

                        if(this.state.orderNo){
                            navigation.goBack()
                        }else{
                            navigation.popToTop()
                        }

                    } catch (e) {

                    }
                }
            })
            .catch((error) => {

            });



    }




}

const styles = StyleSheet.create({

    container: {
        width: screenW,
        flex: 1,
        backgroundColor: '#f6f6f6',
        position: 'relative'
    },

    toplayout: {
        width: screenW,
        height: 50,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#ffffff',
        position: 'relative'
    },
    privewTop: {
        width: screenW / 2,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
    },

    topTitle: {
        fontWeight: '400',
        fontSize: 16,
        color: '#999999'
    },

    topTitleChoose: {
        fontWeight: '500',
        fontSize: 16,
        color: '#333333'
    },

    bottomCheck: {
        backgroundColor: '#FFE001',
        height: 3,
        width: 60,
        position: 'absolute',
        bottom: 0
    },

    scrollViewcontainer: {
    },

    commonTitlsContainer: {
        height: 48,
        backgroundColor: '#ffffff',
        alignItems: 'center',
        flexDirection: 'row',
        position: 'relative'
    },

    commonTitle: {
        fontWeight: '500',
        fontSize: 16,
        color: '#333333',
        marginLeft: 16
    },

    borderBottom: {
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 1,
        position: 'absolute',
        bottom: 0,
        width: screenW,
        marginLeft: 15
    },

    itemContainer: {
        height: 46,
        backgroundColor: '#ffffff',
        alignItems: 'center',
        flexDirection: 'row'
    },

    titleValue: {
        fontWeight: '500',
        fontSize: 14,
        color: '#333333',
        marginLeft: 16
    },

    typeContainer: {
        width: 36,
        height: 16,
        borderRadius: 1,
        borderColor: '#E5E5E5',
        borderWidth: 1,
        marginLeft: 8,
        alignItems: 'center',
        justifyContent: 'center'
    },

    typeText: {
        fontWeight: '500',
        fontSize: 10,
        color: '#666666',
    },

    commonKey: {
        fontWeight: '400',
        fontSize: 14,
        color: '#999999',
        marginLeft: 16,
        width: 90
    },

    commonValue: {
        position: 'absolute',
        marginLeft: 110,
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
    },

    bottomContainer: {
        height: 50,
        width: screenW,
        flexDirection: 'row',
        position: 'absolute'
    },

    beforeContainer: {
        width: 150,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
    },

    beforeTitle: {
        fontWeight: '400',
        fontSize: 16,
        color: '#333333',
    },

    afterContainer: {
        width: screenW - 150,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#FFE000'
    },








})